import createRestfulModule from './restful-module'
import router from '@/router'
/**
 * 用户
 */
export default createRestfulModule({
  state: {
    path: 'users'
  },
  actions: {
    // 获取
    async getCollection({ dispatch }, pagination = {}) {
      const loading = router.app.$loading({ text: '正在查询数据', background: 'rgba(0, 0, 0, 0.7)' })
      try {
        await dispatch('collection', pagination)
      } finally {
        loading.close()
      }
    },
    // 更改
    async updateDocument({ dispatch }, document) {
      const loading = router.app.$loading({ text: '正在修改数据', background: 'rgba(0, 0, 0, 0.7)' })
      try {
        await dispatch('replace', document)
        await dispatch('refreshCollection')
      } finally {
        loading.close()
      }
    },
    // 删除
    async deleteDocument({ dispatch }, document) {
      const loading = router.app.$loading({ text: '正在删除数据', background: 'rgba(0, 0, 0, 0.7)' })
      try {
        await dispatch('remove', document)
        await dispatch('refreshCollection')
      } finally {
        loading.close()
      }
    },
    // 添加
    async createDocument({ dispatch }, document) {
      const loading = router.app.$loading({ text: '正在添加数据', background: 'rgba(0, 0, 0, 0.7)' })
      try {
        await dispatch('create', document)
        await dispatch('refreshCollection')
      } finally {
        loading.close()
      }
    },
    // 刷新获取
    async refreshCollection({ state, dispatch }) {
      const pagination = state.collection.meta.pagination
      await dispatch('getCollection', { pagination })
    },
  }
})